package com.googlecode.garbagecan.cxfstudy.security;

import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.ws.WebServiceException;

import org.apache.cxf.endpoint.Client;
import org.apache.cxf.endpoint.Endpoint;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;
import org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor;
import org.apache.ws.security.WSConstants;
import org.apache.ws.security.handler.WSHandlerConstants;

public class MyClient {
	private static final String address = "http://localhost:9000/ws/security/userService";
	public static void main(String[] args) throws Exception {
		long start = System.currentTimeMillis();
		JaxWsProxyFactoryBean factoryBean = new JaxWsProxyFactoryBean();
		factoryBean.setAddress(address);
		factoryBean.setServiceClass(UserService.class);

		Object obj = factoryBean.create();
		
		Client client = ClientProxy.getClient(obj);
		Endpoint endpoint = client.getEndpoint();
		
		Map<String,Object> props = new HashMap<String,Object>();
		props.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN);
		props.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_TEXT);
		props.put(WSHandlerConstants.PW_CALLBACK_CLASS, ClientUsernamePasswordHandler.class.getName());
		props.put(WSHandlerConstants.USER, "admin");
		WSS4JOutInterceptor wss4JOutInterceptor = new WSS4JOutInterceptor(props);
		endpoint.getOutInterceptors().add(wss4JOutInterceptor);
		
		HTTPConduit conduit = (HTTPConduit) client.getConduit();
		HTTPClientPolicy policy = new HTTPClientPolicy();
		policy.setConnectionTimeout(5 * 1000);
		policy.setReceiveTimeout(5 * 1000);
		conduit.setClient(policy);
		
		UserService service = (UserService) obj;
		try {
			List<User> users = service.list();
			System.out.println(users);
		} catch(Exception e) {
			if (e instanceof WebServiceException 
					&& e.getCause() instanceof SocketTimeoutException) {
				System.err.println("This is timeout exception.");
			} else {
				e.printStackTrace();
			}
		}
		long stop = System.currentTimeMillis();
		System.out.println(stop - start);
	}
}
